package com.diy.sigmund.diycommon.designpatterns.producerconsumer;

import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author ylm-sigmund
 * @since 2022/1/12 17:18
 */
public class ProducerConsumerTest1 {

    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(1);
        Consumer consumer = new Consumer(blockingQueue);
        Producer producer = new Producer(blockingQueue);
        consumer.start();
        producer.start();
    }

    static class Producer extends Thread {

        private BlockingQueue<String> blockingQueue;

        public Producer(BlockingQueue<String> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                String msg = "message" + i;
                try {
                    TimeUnit.MILLISECONDS.sleep(3);
                    blockingQueue.put(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("生产者 " + msg);
            }
            try {
                blockingQueue.put("exit");
            } catch (InterruptedException ignored) {
            }
        }
    }

    static class Consumer extends Thread {

        private BlockingQueue<String> blockingQueue;

        public Consumer(BlockingQueue<String> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            String value;
            try {
                while (!Objects.equals("exit", value = blockingQueue.take())) {
                    TimeUnit.MILLISECONDS.sleep(3);
                    System.out.println("消费者 " + value);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
